package com.ryan.route.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ryan.route.entity.DestCategory;
import com.ryan.route.entity.vo.CategoryVo;
import com.ryan.route.listener.CategoryExcelListener;
import com.ryan.route.mapper.DestCategoryMapper;
import com.ryan.route.service.DestCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 旅游目的地分类 服务实现类
 * </p>
 *
 * @author ryan
 * @since 2020-07-26
 */
@Service
public class DestCategoryServiceImpl extends ServiceImpl<DestCategoryMapper, DestCategory> implements DestCategoryService {

    /**
     * 通过excel添加分类
     * @param file
     * @param categoryService
     */
    @Override
    public void addSubjectByExcel(MultipartFile file, DestCategoryService categoryService) {
        try{
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, CategoryVo.class, new CategoryExcelListener(categoryService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取树状分类数据
     * @return
     */
    @Override
    public List<DestCategory> listWithTree() {
        //首先获取所有数据
        List<DestCategory> destCategories = baseMapper.selectList(null);
        //找到所有的一级分类
        List<DestCategory> level1Menus = destCategories.stream().filter(destCategory ->
                //字符串一定要使用equals
                destCategory.getParentId().equals("0")
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, destCategories));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 递归查询所有的子菜单
     * @param root
     * @param destCategories
     * @return
     */
    private List<DestCategory> getChildrens(DestCategory root, List<DestCategory> destCategories) {

        List<DestCategory> children = destCategories.stream().filter(destCategory -> {
            return destCategory.getParentId().equals(root.getId());
        }).map(destCategory -> {
            //递归找到子菜单
            destCategory.setChildren(getChildrens(destCategory, destCategories));
            return destCategory;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }
}
